<template>
  <div class="app-container">
    <page-header
      title="频道设置"
      desc="店铺商品限时折扣促销活动设置及管理"
      show-back
    />
    <div class="buttons">
      <el-button
        :disabled="canSubmit"
        @click="onSubmit"
      >提交保存</el-button>
      <el-button @click="resetChecked">清空</el-button>
    </div>
    <el-input
      v-model="filterText"
      placeholder="输入关键字进行过滤"
    />
    <el-tree
      ref="tree"
      :data="categorys"
      show-checkbox
      node-key="id"
      highlight-current
      :props="defaultProps"
      :filter-node-method="filterNode"
      :default-checked-keys="checks"
      @check-change="onChange"
    />
  </div>
</template>
<script>
import PageHeader from '@/components/PageHeader'
export default {
  components: {
    PageHeader
  },
  data() {
    return {
      channel: null,
      drawer: false,
      loaded: false,
      dialogFormVisible: false,
      checks: [],
      categorys: [],
      results: [],
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  inject: ['goBack'],
  computed: {
    channelId() {
      return this.$route.params.id
    },
    canSubmit() {
      if (this.results.length > 0) {
        return this.compareArray(this.checks, this.results)
      } else {
        return true
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.onLoad()
  },
  mounted() {},
  methods: {
    compareArray(that, array) {
      if (!array.length) return false
      // compare lengths - can save a lot of time
      if (that.length !== array.length) return false

      for (var i = 0, l = that.length; i < l; i++) {
        // Check if we have nested arrays
        if (that[i] instanceof Array && array[i] instanceof Array) {
          // recurse into the nested arrays
          if (!this.compareArray(that[i], array[i])) {
            return false
          }
        } else if (that[i] !== array[i]) {
          // Warning - two different object instances will never be equal: {x:20} != {x:20}
          return false
        }
      }
      return true
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    onLoad() {
      this.$http.channel.sourceCategory(this.channelId).then(res => {
        const { categorys, checks } = res.data
        this.categorys = categorys
        this.checks = checks
      })
    },
    onRefresh() {
      console.log('onRefresh')
      this.dialogFormVisible = false
      this.onLoad()
    },
    onDialogSubmit() {
      var $el = this.$refs
      if ($el.dialogForm) {
        $el.dialogForm.onSubmit()
      } else {
        console.log('refs:', $el)
      }
    },
    getCheckedNodes() {
      console.log(this.$refs.tree.getCheckedNodes())
    },
    getCheckedKeys() {
      console.log(this.$refs.tree.getCheckedKeys())
    },
    setCheckedNodes() {
      this.$refs.tree.setCheckedNodes([
        {
          id: 5,
          label: '二级 2-1'
        },
        {
          id: 9,
          label: '三级 1-1-1'
        }
      ])
    },
    setCheckedKeys() {
      this.$refs.tree.setCheckedKeys([3])
    },
    resetChecked() {
      this.$refs.tree.setCheckedKeys([])
      this.results = []
    },
    onSubmit() {
      console.log(this.results)
      this.$http.channel
        .updateSource({
          items: this.results,
          channel_id: this.channelId
        })
        .then(res => {
          console.log(res)
          this.goBack()
        })
    },
    onChange() {
      this.results = this.$refs.tree.getCheckedKeys(true)
    },
    onChangeParent() {
      var checks = this.$refs.tree.getCheckedNodes(false, true)
      var parents = checks.filter(item => {
        return !item.parent_id
      })
      var nodes = parents.map(item => {
        return this.$refs.tree.getNode(item)
      })
      var checkeds = []
      this.filterMerges(nodes, checkeds)
      // this.$emit('finished', { id: 12222 })
      this.results = checkeds
    },
    filterMerges(nodes, checkeds = []) {
      var uncheckNodes = nodes.filter(node => {
        if (node.checked) {
          checkeds.push(node.data.id)
        }
        return !node.checked
      })
      for (var i = 0; i < uncheckNodes.length; i++) {
        var item = uncheckNodes[i].data
        if (item.children) {
          var childrenNodes = item.children.map(c => {
            return this.$refs.tree.getNode(c)
          })
          this.filterMerges(childrenNodes, checkeds)
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.preview-drawer {
  .em-phone {
    width: 80%;
  }
  ::v-deep .el-drawer__body {
    display: flex;
    flex-direction: column;
  }
  &__actions {
    flex: 1;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
